import sys

from PyQt5.QtCore import QCoreApplication, QThread
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QMessageBox, QLabel, QVBoxLayout

from insert_title_to_content_main import process


class BackgroundWorker(QThread):
    def __init__(self, folder_path, parent=None):
        super().__init__(parent)
        self.folder_path = folder_path

    def run(self):
        # 在后台运行的处理方法
        # 将你的代码放在这里
        # 例如，执行某个耗时的任务
        # 这是一个示例，在后台运行 5 秒钟
        process(self.folder_path)

    def quit(self):
        # 重载 quit 方法，确保线程可以正常退出
        self.terminate()
        self.wait()


class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("批量插入标题到正文工具")
        self.setGeometry(300, 300, 500, 200)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.lbl_selected_folder = QLabel(self)
        self.lbl_selected_folder.setText("您还没有选择文件")
        self.layout.addWidget(self.lbl_selected_folder)

        self.btn_select_folder = QPushButton("选择文件夹", self)
        self.btn_select_folder.clicked.connect(self.folder_dialog)
        self.btn_select_folder.setFixedHeight(40)  # 设置高度为30像素
        self.btn_select_folder.setFixedWidth(300)  # 设置高度为30像素
        self.layout.addWidget(self.btn_select_folder)

        self.btn_start_process = QPushButton("开始执行", self)
        self.btn_start_process.clicked.connect(self.start_process)
        self.btn_start_process.setFixedHeight(40)  # 设置高度为30像素
        self.btn_start_process.setFixedWidth(200)  # 设置高度为30像素
        self.layout.addWidget(self.btn_start_process)

        self.folder_path = ""

    def folder_dialog(self):
        folder_dialog = QFileDialog()
        self.folder_path = folder_dialog.getExistingDirectory(self, "选择文件夹")
        if self.folder_path:
            self.lbl_selected_folder.setText(f"批处理文件夹: {self.folder_path}")

    def start_process(self):
        if not self.folder_path:
            QMessageBox.warning(self, "Error", "请您先选择一个文件夹!")
            return

        # 创建后台工作线程
        self.worker = BackgroundWorker(self.folder_path)
        self.worker.finished.connect(self.process_finished)
        self.worker.start()

    def process_finished(self):
        QMessageBox.information(self, "成功", "成功处理!")

        # 退出应用程序
        QCoreApplication.quit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    widget.show()
    sys.exit(app.exec_())
